<template>
  <div class="app-container">
    <!-- 条件搜索 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入动态标题" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="所属乡镇" prop="townShipId">
        <el-select v-model="queryParams.townShipId" placeholder="请选择" @change="townChange">
          <el-option v-for="item in townList" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用户" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入发布用户" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="发布时间" prop="creatTime">
        <el-date-picker v-model="queryParams.creatTime" value-format="yyyy-MM-dd" type="date" placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="是否精选" prop="flag">
        <el-select v-model="queryParams.flag" placeholder="请选择">
          <el-option :label="'是'" :value="true"></el-option>
          <el-option :label="'否'" :value="false"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择">
          <el-option :label="'未审核'" :value="0"></el-option>
          <el-option :label="'审核通过'" :value="1"></el-option>
          <el-option :label="'审核失败'" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['application:examine:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini"  @click="handleUpdate"
          v-hasPermi="['application:examine:edit']">修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="handleDelete"
          v-hasPermi="['application:examine:remove']">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['application:examine:export']">导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!--  table表单-->
    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center" />
      <el-table-column label="标签" align="center" prop="labelName">
        <template slot-scope="scope">
          <el-tag v-for="tag in scope.row.labelName.split(',')" :key="tag" type="success">
            {{ tag }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="title" width="150" />
      <!-- <el-table-column label="内容" align="center" prop="textContent" width="400">
        <template slot-scope="scope">
          <div :title="scope.row.textContent" v-html="scope.row.textContent" style="height:100px;overflow:hidden"></div>
        </template>
      </el-table-column> -->
      <el-table-column label="图片" align="center" prop="image" width="180">
        <template slot-scope="scope">
          <el-image :lazy="true" :preview-src-list="scope.row.previewImg" v-for="(item, index) in scope.row.imagesUrl"
            :key="index" :src="baseurl + item" style="width: 50px; height: 50px"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="发布地址" align="center" prop="locationName" width="250" />
      <el-table-column label="发布时间" align="center" prop="creatTime" width="160" />
      <el-table-column label="发布用户" align="center" prop="name" width="100" />
      <el-table-column label="是否精选" width="150px" align="center" prop="state">
        <template slot-scope="scope">
          <el-switch style="display: block" v-model="scope.row.flag" active-color="#13ce66" inactive-color="#ff4949"
            active-text="是" inactive-text="否" @change="selected(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="state">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.state === 0 ? 'info' : scope.row.state === 1 ? 'success' : scope.row.state === 2 ? 'danger' : 'warning'">
            {{ scope.row.state === 0 ? "等待审核" : scope.row.state === 1 ? "审核通过" : scope.row.state === 2 ? "审核失败" : "暂无"
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="100">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['application:sort:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['application:sort:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改大类对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="1000px" append-to-body
      :before-close="handleClose" @close="dioClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标签" prop="labelId">
          <el-checkbox-group v-model="form.labelId">
            <el-checkbox v-for="(item, index) in labelList" :key="index" :label="item.id">{{ item.labelName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="内容" prop="textContent">
          <editor v-model="form.textContent" v-if="open" :min-height="50" />
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <imageUpload v-model="form.image" @uploadImage="uploadimg" @remove="removeImg" :limit="9" />
        </el-form-item>
        <el-form-item label="发布地址" prop="locationName">
          <zxMap :value="latLng" :address="form.locationName" @input="mapClick" v-if="open"></zxMap>
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="form.longitude" placeholder="请输入经度" disabled />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="form.latitude" placeholder="请输入纬度" disabled />
        </el-form-item>
        <el-form-item label="发布用户" prop="userId">
          <el-select v-model="form.userId" placeholder="请先选择用户">
            <el-option v-for="item in userList" :key="item.id" :label="item.userName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属乡镇" prop="townShipId">
          <el-select v-model="form.townShipId" placeholder="请选择" @change="townChange">
            <el-option v-for="item in townList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属景区" prop="landscapesId">
          <el-select v-model="form.landscapesId" placeholder="请先选择所属景区">
            <el-option v-for="item in sinceSpotList" :key="item.id" :label="item.landscapesName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属场所" prop="venueId">
          <el-select v-model="form.venueId" placeholder="请先选择所属乡镇">
            <el-option v-for="item in placeList" :key="item.id" :label="item.venueName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否精选" prop="state">
          <el-radio-group v-model="form.flag">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核状态" prop="state">
          <el-radio-group v-model="form.state" @change="toExamineChange(form.state)">
            <el-radio :label="0">未审核</el-radio>
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="opinion" v-if="form.state === 2">
          <el-input type="textarea" v-model="form.opinion" placeholder="请输入不通过原因"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  exportSort,
  userDynamics_list,
  userDynamics_update,
  userDynamics_delete,
  userDynamics_examine,
  label_list,
  userDynamics_add,
  allUser_list,
  userDynamics_info,
} from "@/api/application/sort/sort";
import {
  town_list,
  getLandscapes_list,
  getPlace_list,
} from "@/api/view/activity_information";
import ImageUpload from "@/components/UploadImage";
import zxMap from "@/components/map/index";
import editor from "@/components/Editor";
export default {
  name: "Sort",
  components: {
    ImageUpload,
    zxMap,
    editor,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户动态表格数据
      list: [],
      //乡镇列表
      townList: [],
      //景区列表
      sinceSpotList: [],
      //场所列表
      placeList: [],
      //用户列表
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        name: null,
        status: null,
        creatTime: null,
        flag: null,
        townShipId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        labelId: [{ required: true, message: '请选择', trigger: 'blur' }],
        title: [{ required: true, message: '请输入', trigger: 'blur' }],
        textContent: [{ required: true, message: '请输入', trigger: 'blur' }],
        image: [{ required: true, message: '请选择', trigger: 'change' }],
        locationName: [{ required: true, message: '请输入', trigger: 'blur' }],
        state: [{ required: true, message: '请选择', trigger: 'blur' }],
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        userId: [{ required: true, message: '请选择', trigger: 'change' }],
        longitude: [{ required: true, message: '请在上方地图获取经纬度', trigger: 'blur' }],
        latitude: [{ required: true, message: '请在上方地图获取经纬度', trigger: 'blur' }],
        opinion: [{ required: true, message: '请输入', trigger: 'blur' }],
      },
      labelList: [],
      latLng: "",
    };
  },
  created() {
    if (this.$route.query.searchName) {
      this.queryParams.title = this.$route.query.searchName;
      this.getList();
    };
    this.getList();
    this.getLabelList();
    this.getUserInfo();
    this.getTown();
  },
  methods: {
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
          // location.reload();
        })
        .catch((_) => { });
    },
    // 表单重置
    reset() {
      this.form = {
        title: null,
        textContent: null,
        image: null,
        locationName: null,
        creatTime: null,
        state: null,
        name: null,
        longitude: null,
        latitude: null,
        opinion: null,
        venueId: null,
        landscapesId: null,
        townShipId: null,
        labelId: [],
        flag: false,
      };
      this.resetForm("form");
    },
    /** 查询动态列表 */
    async getList() {
      this.loading = true;
      let res = await userDynamics_list(this.queryParams);
      let { code, rows, total } = res;
      if (code === 200) {
        rows.forEach((item) => {
          let previewImg = []; //图片预览数组
          item.imagesUrl = item.imageScale.split(",");
          item.imagesUrl.forEach((val) => {
            previewImg.push(this.baseurl + val);
            item.previewImg = previewImg;
          });

        });
        this.list = rows;
        this.total = total;
        this.loading = false;
      }
    },
    /* 查询标签列表 */
    async getLabelList() {
      let res = await label_list();
      let { code, data } = res;
      if (code === 200) {
        this.labelList = data;
      };
    },
    /* 获取用户信息列表 */
    async getUserInfo() {
      let res = await allUser_list();
      let { code, data } = res;
      if (code === 200) {
        this.userList = data;
      };
    },
    /* 获取乡镇列表 */
    getTown() {
      town_list().then(res => {
        console.log(res.data, 'town');
        this.townList = res.data;
      });
    },
    /* 获取景区列表 */
    getSinceSpot(id) {
      getLandscapes_list({ townShipId: id }).then(res => {
        console.log(res.data, 'Landscapes');
        this.sinceSpotList = res.data;
      });
    },
    /* 获取场所列表 */
    getPlace(id) {
      getPlace_list({ townShipId: id }).then(res => {
        console.log(res.data, 'place');
        this.placeList = res.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.placeList = [];
      this.sinceSpotList = [];
      this.title = "添加用户动态";
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.placeList = [];
      this.sinceSpotList = [];
      this.reset();
      this.title = "修改用户动态";
      userDynamics_info({ id: row.id }).then(res => {
        console.log(res,'res');
        this.latLng = res.data.longitude + "," + res.data.latitude;
        res.data.labelId = res.data.labelId.split(",").map(Number);
        this.form = res.data;
        this.open = true;
        if (res.data.townShipId) {
          this.getSinceSpot(row.townShipId);
          this.getPlace(row.townShipId);
        };
      });
    },
    //审核状态change事件
    toExamineChange(val){
      if(val === 2){
        this.form.opinion = null;
      };
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          this.form.labelId = this.form.labelId.join(",");
          if (this.form.id != null) {
            let res = await userDynamics_update(this.form);
            let { code } = res;
            if (code === 200) {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            };
          } else {
            let res = await userDynamics_add(this.form);
            let { code } = res;
            if (code === 200) {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            };
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除动态标题为"' + row.title + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        let res = await userDynamics_delete(ids);
        let { code } = res;
        if (code === 200) {
          this.getList();
          this.msgSuccess("删除成功");
        };
      }).catch(err => {
        this.msgInfo("取消删除");
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有大类数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportSort(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
    //图片上传事件
    uploadimg(e) {
      this.form.image = e;
    },
    //删除图片事件
    removeImg(e) {
      this.form.image = e;
    },
    /* 地图事件 */
    mapClick(e) {
      console.log(e, 'eeee');
      let latlng = e.lnglat.split(",");
      this.form.longitude = latlng[0];
      this.form.latitude = latlng[1];
      this.form.locationName = e.address;
    },
    /* dio关闭时触发 */
    dioClose() {
      this.latLng = "";
    },
    /* 所属乡镇下拉框change事件 */
    townChange(id) {
      this.getSinceSpot(id);
      this.getPlace(id);
    },
    /* 是否精选change事件 */
    selected(e) {
      userDynamics_update(e).then(res => {
        this.msgSuccess(res.msg);
        this.getList();
      }).catch(err => {
        this.getList();
      });
    },
  },
};
</script>
